package com.shiku.imclient;

import com.google.common.collect.Sets;
import com.shiku.imserver.common.message.MessageReceiptStatus;
import com.shiku.imserver.common.proto.MessageProBuf;
import com.shiku.imserver.common.tcp.TcpPacket;
import com.shiku.imserver.common.utils.ProBufUtils;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class SendMessageReceiptRunnable implements Runnable {
    private BaseIMClient imClient;
    private Set<String> messageSet = Sets.newConcurrentHashSet();

    public SendMessageReceiptRunnable(BaseIMClient imClient2) {
        this.imClient = imClient2;
        imClient2.getExecutor().scheduleAtFixedRate(this, 2, 2, TimeUnit.SECONDS);
    }

    public void putMessageReceipt(String messageId) {
        this.messageSet.add(messageId);
    }

    public void run() {
        if (!this.messageSet.isEmpty()) {
            StringBuffer messageId = new StringBuffer();
            synchronized (this.messageSet) {
                for (String msgId : this.messageSet) {
                    messageId.append(msgId).append(",");
                }
                this.messageSet.clear();
            }
            sendMessageReceipt(messageId.toString());
        }
    }

    public void sendMessageReceipt(String messageId) {
        MessageReceiptStatus receiptStatus = new MessageReceiptStatus();
        receiptStatus.setMessageHead(this.imClient.createMessageHead((byte) 1, null));
        receiptStatus.setMessageId(messageId);
        receiptStatus.setStatus((byte) 2);
        TcpPacket packet = ProBufUtils.encodeTcpPacket(receiptStatus, MessageProBuf.MessageReceiptStatusProBuf.getDescriptor());
        packet.setCommand((short)11);
        this.imClient.sendImPacket(packet);
    }
}
